package xiaohu.ODImportant;

import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        while (scanner.hasNextInt()) {
            int m = scanner.nextInt();
            int n = scanner.nextInt();
            int[][] arr = new int[m][n];
            for (int i = 0; i < n; i++) {
                for (int j = 0; j < n; j++) {
                    arr[i][j] = scanner.nextInt();
                }
            }

            int max = 0;//记录最大可以移动的格数

            for (int i = 0; i < m; i++) {
                for (int j = 0; j < n; j++) {
                    int[][] result = new int[m][n];//以(i,j)为起点，移动，
                    int count = 0;//记录步数
                    result[i][j] = 1;
                    count = 1;
                    // 从(i,j)开始，向右，向下，向右下移动
                    count=keep(arr, result, i, j, count, m, n);
                    max = Math.max(max, count);
                }
            }
            System.out.println(max);
        }
    }

    private static int keep(int[][] arr, int[][] result, int i, int j, int count, int m, int n) {
        if (j + 1 < n && Math.abs(arr[i][j + 1] - arr[i][j]) <= 1 && result[i][j + 1] == 0) {
            result[i][j + 1] = 1;
            count++;
            count=keep(arr, result, i, j + 1, count, m, n);
//            // 回溯
//            result[i][j + 1] = 0;
//            count--;
        }
        if (i + 1 < m && Math.abs(arr[i + 1][j] - arr[i][j]) <= 1 && result[i + 1][j] == 0) {
            result[i + 1][j] = 1;
            count++;
            count=keep(arr, result, i + 1, j, count, m, n);
//            // 回溯
//            result[i + 1][j] = 0;
//            count--;
        }
        if (j - 1 >= 0 && Math.abs(arr[i][j - 1] - arr[i][j]) <= 1 && result[i][j - 1] == 0) {
            result[i][j - 1] = 1;
            count++;
            count=keep(arr, result, i, j - 1, count, m, n);
//            // 回溯
//            result[i][j - 1] = 0;
//            count--;
        }
        if (i - 1 >= 0 && Math.abs(arr[i - 1][j] - arr[i][j]) <= 1 && result[i - 1][j] == 0) {
            result[i - 1][j] = 1;
            count++;
            count=keep(arr, result, i - 1, j, count, m, n);
//            // 回溯
//            result[i - 1][j] = 0;
//            count--;
        }
        return count;
    }
}
